<template>
  <div>
    <!-- 交付经理填写试运行信息 -->
    <div class="desc-item">
      <div class="form-item">试运行信息</div>
      <DynamicDescription
        ref="dynamicDescription"
        :descriptions="testRunDetails.testRunInfoDesc"
        :descriptForm="testRunDetails.testRunInfoForm"
        :readOnly="!isShowApprovalOperation('first')"
        :column="1"
      />
      <div v-if=" projectFiles[processStageName].length > 0">
        <div class="table-title">上传附件</div>
        <FilesUpload
          ref="filesUploadRef"
          :fileTypes="projectFiles[processStageName]"
          :projectInfo="projectInfo"
          :readOnly="!isShowApprovalOperation('first')"
          @getProjectFilesInfo="$emit('getProjectFilesInfo')"
        />
      </div>
      <div v-if="isShowApprovalOperation('first')">
        <div class="form-item">审批信息</div>
        <div class="table-title" > 下一环节 - 建设单位部门经理审批 </div>
        <DynamicDescription
          :descriptions="testRunDetails.testRunSecondInfoDesc"
          :readOnly="true"
          :column="2"
        />
        <ApprovalOpinion
          ref="approvalOpinionRef"
          v-model="approvalOpinionData" 
          required 
          label="审批意见"
        />
        <div class="mb-16 flex">
          <el-button
            class="ml-auto"
            type="primary"
            size="default"
            @click="approvalProcess('agree', 'projectManager', projectInfo.construction_department_manager_id)"
          >同意</el-button>
        </div>
      </div>
      <!-- 地市三级经理审批 -->
      <div v-if="isShowApprovalOperation('second')">
        <div class="form-item">审批信息</div>
        <ApprovalOpinion
          ref="approvalOpinionRef"
          v-model="approvalOpinionData" 
          required 
          label="审批意见"
        />
        <div class="mb-16 flex">
          <el-button
            class="ml-auto"
            type="danger"
            size="default"
            @click="approvalProcess('refuse', 'constructionDepartmentManager')"
          >驳回</el-button>
          <el-button
            type="primary"
            size="default"
            @click="approvalProcess('agree', 'constructionDepartmentManager')"
          >同意</el-button>
        </div>
      </div>
    </div>

  </div>
</template>

<script setup>
import * as KmsApi from '@/api/project/kms'
import * as BpmApi from '@/api/project/bpm'
import * as IctApi from '@/api/project/ict'
import DynamicDescription from '@/views/project/projectDetails/components/DynamicDescription.vue'
import FilesUpload from '@/views/project/projectDetails/components//FilesUpload.vue';
import { ref, toRefs } from 'vue'
import ApprovalOpinion from '@/views/project/components/ApprovalOpinion.vue'

// emit事件合集
const emit = defineEmits(['getApprovalProcess', 'getProjectInfo', 'getProjectFilesInfo']);

// Props传值
const props = defineProps({
  isShowApprovalOperation: Function,
  projectInfo: Object,
  testRunDetails: Object,
  processStageName: String,
  taskName: String,
  role: String,
  processList: Array,
  projectFiles: Object
})
const { isShowApprovalOperation, projectInfo, testRunDetails, processStageName, taskName, role, processList } = toRefs(props);

// 动态详情组件ref对象
const dynamicDescription = ref()
// 审批意见
const approvalOpinionData = ref('同意')
const approvalOpinionRef = ref()
// 创建对文件上传子组件的引用
const filesUploadRef = ref(null);

const approvalProcess = async (result, currentRole, nextRoleId) => {

  try {
    if (result === 'agree') {
      await Promise.all([
        dynamicDescription.value.validateForm(),
        approvalOpinionRef.value.validateForm()
      ])
      if (filesUploadRef.value && !filesUploadRef.value?.validateFiles()) {
        return;
      }
    } else {
      await approvalOpinionRef.value.validateForm()
    }
    
    ElMessageBox.confirm(`是否${result === 'agree' ? '同意' : '驳回'}该流程单？`, '提示', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(async () => {
      const approvalFormData = dynamicDescription.value.getFormData()
      
      if (result === 'agree') {
        const agreeProcessData = {
          assignedUserIds: [nextRoleId],
          id: processList.value[0].id,
          reason: approvalOpinionData.value || '同意',
          copyUserIds: [],
          variables: {}
        }
        
        if (currentRole === 'projectManager') {
          projectInfo.value = Object.assign(projectInfo.value, approvalFormData)
        }

        const agreeData = {
          update: true,
          project_index_do: projectInfo.value,
          task_approve_req_vo: agreeProcessData
        }

        if (currentRole === 'projectManager') {
          await IctApi.agreeProjectProcess(agreeData).then(() => {
            emit('getApprovalProcess')
            emit('getProjectInfo')
          })
        } else {
          await IctApi.agreeTestRunDepartmentManagerProcess(agreeData).then(() => {
            emit('getApprovalProcess')
            emit('getProjectInfo')
          })
        }

      } else if (result === 'refuse') {
        const refuseData = {
          id: processList.value[0].id,
          reason: approvalOpinionData.value || '不同意'
        }
        await IctApi.refuseTestRunProcess(refuseData).then(() => {
          emit('getApprovalProcess')
        })
      }
      ElMessage({
        type: 'success',
        message: '提交成功'
      })
    })
  } catch (error) {
    ElMessage({
      type: 'error',
      message: '请按照格式要求填写信息'
    })
  }
}

</script>

<style lang="scss" scoped>
@import url('@/views/project/projectDetails/styles/transfer.css');

</style>